package com.tumanex.activity;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.tumanex.R;
import com.tumanex.socialshare.FacebookShare;
import com.tumanex.socialshare.SitesApp;

/**
 * 
 * @author artemka
 * 
 */
public class WallPostActivity extends Activity implements OnClickListener,
		android.content.DialogInterface.OnClickListener {

	private static final int FACEBOOK_ITEM = 0;
	private static final int VKONTAKTE_ITEM = 1;

	private static final String FACEBOOK = "FACEBOOK";
	private static final String VKONTAKTE = "VKONTAKTE";

	private static volatile boolean doAnimation;

	private static final int ANIM_PROG_OPER_1 = 101;
	private static final int ANIM_PROG_OPER_2 = 102;
	private static final int AMIN_PROG_OPER_3 = 103;

	private static final int DALEY_PROG_ANIM = 700;

	private String currentSocNet;

	private Thread animThread;

	private View downloadView;

	private AlertDialog downloadDialog;
	private AlertDialog chooseDialog;

	private static final int ERROR_OPER = 2;
	private static final int SUCS_OPER = 1;

	private static final int PUBLISH_BT_ENABLE = 4;

	private static final int REQUEST_LOGIN = 1;

	SitesApp oauth;

	private Handler mHandler;

	private ImageView mImageView;
	private EditText mEdit;
	private Button mLoginBt;
	private Button mPublishBt;

	private FacebookShare mFacebookShare;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_publish);

		setupComponents();

		mFacebookShare = new FacebookShare(WallPostActivity.this, mHandler);

		oauth = new SitesApp(getApplicationContext());

		if (getIntent().hasExtra(Intent.EXTRA_STREAM)) {

			Uri uri = (Uri) getIntent().getExtras().get(Intent.EXTRA_STREAM);
			mImageView.setImageURI(uri);
		}

		checkTokens();
	}

	public void setupComponents() {

		mImageView = (ImageView) findViewById(R.id.user_picture);

		mLoginBt = (Button) findViewById(R.id.bt_login);
		mLoginBt.setOnClickListener(this);

		mEdit = (EditText) findViewById(R.id.txt_comment);

		mPublishBt = (Button) findViewById(R.id.bt_publish);
		mPublishBt.setOnClickListener(this);

		CreateDowloadDialog();

		mHandler = new Handler() {

			public void handleMessage(android.os.Message msg) {

				switch (msg.what) {

				case SUCS_OPER:

					mPublishBt.setText(R.string.tl_bt_publish);
					mLoginBt.setEnabled(true);
					mPublishBt.setEnabled(true);

					stopDwnldWithMessage(getString(R.string.dowload_succ));

					break;

				case ERROR_OPER:

					mPublishBt.setText(R.string.tl_bt_publish);
					mLoginBt.setEnabled(true);
					mPublishBt.setEnabled(true);

					stopDwnldWithMessage(getString(R.string.download_error));

					break;

				case PUBLISH_BT_ENABLE:

					mPublishBt.setEnabled(true);

				case ANIM_PROG_OPER_1:

					((TextView) downloadView.findViewById(R.id.dwnl_status))
							.setText(R.string.dowload_mesg1);
					break;

				case ANIM_PROG_OPER_2:

					((TextView) downloadView.findViewById(R.id.dwnl_status))
							.setText(R.string.dowload_mesg2);
					break;

				case AMIN_PROG_OPER_3:

					((TextView) downloadView.findViewById(R.id.dwnl_status))
							.setText(R.string.dowload_mesg3);
					break;
				}

			}

		};

	}

	public void onClick(View v) {

		switch (v.getId()) {

		case R.id.bt_login:

			showChooseDialog();
			break;

		case R.id.bt_publish:

			mPublishBt.setEnabled(false);
			mLoginBt.setEnabled(false);

			downloadDialog.show();

			mPublishBt.setText(R.string.tl_bt_publish_prog);

			startAnimProcessing();

			if (currentSocNet.equals(VKONTAKTE))
				createVkWallPostThread();

			if (currentSocNet.equals(FACEBOOK))
				mFacebookShare.Share(getComment(), getImageViewBitmap());

		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {

		switch (id) {

		case R.id.dialog_auth_error:
			return createDialogErrorAuth();

		default:
			return super.onCreateDialog(id);
		}

	}

	private void showChooseDialog() {

		AlertDialog.Builder adb = new AlertDialog.Builder(this);

		adb.setTitle(R.string.choose_site).setItems(R.array.choose, this);

		chooseDialog = adb.create();
		chooseDialog.show();

	}

	private void CreateDowloadDialog() {

		AlertDialog.Builder adb = new AlertDialog.Builder(this);

		downloadView = getLayoutInflater().inflate(R.layout.download_dialog,
				null);

		adb.setView(downloadView);

		adb.setTitle(R.string.dowload_tilte);

		downloadDialog = adb.create();

		downloadView.findViewById(R.id.dwnlOkBt).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {

						downloadDialog.hide();
					}
				});

	}

	private void stopDwnldWithMessage(String message) {

		stopAnimProcessing();

		((TextView) downloadView.findViewById(R.id.dwnl_status))
				.setText(message);

		((ProgressBar) downloadView.findViewById(R.id.d_progressBar))
				.setVisibility(ProgressBar.GONE);

		downloadDialog.show();

	}

	private void startAnimProcessing() {

		doAnimation = true;

		animThread = new Thread() {

			@Override
			public void run() {

				while (true) {

					try {
						if (!doAnimation)
							return;
						mHandler.sendEmptyMessage(ANIM_PROG_OPER_1);
						sleep(DALEY_PROG_ANIM);
						if (!doAnimation)
							return;
						mHandler.sendEmptyMessage(ANIM_PROG_OPER_2);
						sleep(DALEY_PROG_ANIM);
						if (!doAnimation)
							return;
						if (!doAnimation)
							return;
						mHandler.sendEmptyMessage(AMIN_PROG_OPER_3);
						sleep(DALEY_PROG_ANIM);
					} catch (Exception e) {

					}
				}

			}
		};

		animThread.start();

	}

	private void stopAnimProcessing() {

		doAnimation = false;
		try {
			animThread.join();
		} catch (InterruptedException e) {
		}
	}

	public void onClick(DialogInterface dialog, int which) {

		Intent intent;

		switch (which) {

		case FACEBOOK_ITEM:

			currentSocNet = FACEBOOK;
			mFacebookShare.loginIn();

			break;

		case VKONTAKTE_ITEM:

			intent = new Intent(this, LoginActivity.class);
			currentSocNet = VKONTAKTE;
			intent.putExtra("socnet", currentSocNet);
			startActivityForResult(intent, REQUEST_LOGIN);

			break;
		}

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == REQUEST_LOGIN) {
			if (resultCode == RESULT_OK) {

				String[] token = (String[]) data
						.getCharSequenceArrayExtra("token");

				String accessToken = token[0].split("access_token=")[1];
				String expires = token[1].split("expires_in=")[1];
				String userId = token[2].split("user_id=")[1];

				oauth.saveAccessToken(accessToken, expires, userId);

				mPublishBt.setEnabled(true);

			} else {

				showDialog(R.id.dialog_auth_error);
			}
		}
	}

	private boolean creatVkWallPost() {

		if (!oauth.hasAccessToken())
			return false;

		Boolean getUrl = oauth.getWallUploadVkServer();

		if (!getUrl)
			return false;

		Boolean upPhoto = oauth.uploadImage(
				oauth.getResponseParams().get("upload_url"),
				getImageViewBitmap());
		if (!upPhoto)
			return false;

		Boolean savePhoto = oauth.VkSaveWallPhoto();
		if (!savePhoto)
			return false;

		Boolean pos = oauth.postToVkWall(getComment());
		if (!pos)
			return false;

		return true;
	}

	private void createVkWallPostThread() {

		new Thread() {

			@Override
			public void run() {
				Boolean res = creatVkWallPost();
				if (res) {
					mHandler.sendEmptyMessage(SUCS_OPER);
				} else {
					mHandler.sendEmptyMessage(ERROR_OPER);
				}
			}

		}.start();
	}

	public Bitmap getImageViewBitmap() {

		BitmapDrawable drawable = (BitmapDrawable) mImageView.getDrawable();
		Bitmap bitmap = drawable.getBitmap();

		return bitmap;
	}

	public String getComment() {

		String com = mEdit.getText().toString();
		return com;
	}

	public Dialog createDialogErrorAuth() {

		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		adb.setTitle(R.string.auth_error_tl);
		adb.setMessage(R.string.auth_error_mes);

		adb.setNeutralButton(getString(R.string.ok),
				new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {

						dialog.dismiss();
					}
				});

		return adb.create();
	}

	public boolean checkTokens() {

		if (oauth.hasAccessToken()) {

			mPublishBt.setEnabled(true);
			currentSocNet = VKONTAKTE;
			return true;
		}

		if (mFacebookShare.isSessionValid()) {

			mPublishBt.setEnabled(true);
			currentSocNet = FACEBOOK;
			return true;
		}

		mPublishBt.setEnabled(false);
		return false;
	}
}